<template>
  <div class="workOrderDetail">
    <FixedOperation>
      <el-row>
        <el-col :span="4" :offset="20" class="flex justify-end">
          <el-button
            @click="toProcessDetail"
            type="primary"
            plain
            :disabled="ToProcess"
            >查看流程</el-button
          >
          <el-button
            @click="transFormTask"
            type="primary"
            plain
            :disabled="!processOver"
            >转任务</el-button
          >
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container">
      <div class="part" style="margin-top: 0">
        <title-name
          title="工单基本信息"
          icon="i-carbon-bookmark-filled"
        ></title-name>
      </div>
      <el-form
        :model="baseForm"
        label-width="120px"
        class="baseInfo"
        ref="baseWorkOrder"
      >
        <el-row>
          <el-col :offset="3" :span="9">
            <el-form-item label="工单主题:" prop="theme">
              <el-input
                v-model="baseForm.theme"
                placeholder="请输入工单主题"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="工单编码:" prop="num">
              <el-input
                v-model="baseForm.num"
                :readonly="true"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="9">
            <el-form-item label="工单级别:" prop="level">
              <el-radio-group v-model="baseForm.level" class="ml-4">
                <el-radio
                  v-for="item in work_order_level"
                  :label="item.value"
                  size="large"
                  disabled
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item></el-col
          >
          <el-col :span="9">
            <el-form-item label="工单类型:" prop="type">
              <el-tree-select
                v-model="baseForm.type"
                placeholder="请选择业务分类"
                :data="workOrderType"
                default-expand-all
                disabled
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :offset="3" :span="9">
            <el-form-item label="发起单位:" prop="发起单位">
              <div>{{ baseForm.companyName + ' ' + baseForm.deptName }}</div>
            </el-form-item></el-col
          >
          <el-col :span="9">
            <el-form-item label="发起人:" prop="发起人">
              <div>
                {{ baseForm.sponsorName + ' ' + baseForm.sponsorPhone }}
              </div>
            </el-form-item></el-col
          >
        </el-row>
      </el-form>
      <div class="part">
        <title-name
          :title="`工单详细信息`"
          icon="i-carbon-bookmark-filled"
        ></title-name>
      </div>
      <el-form :model="detailForm" label-width="120px" ref="detailWorkorder">
        <el-row>
          <!-- 销售订单 -->
          <el-col :offset="3" :span="9" v-if="orderType === '售后工单'">
            <el-form-item label="客户名称:" prop="customerId">
              <el-input
                v-model="detailForm.customerIdCn"
                placeholder="请选择客户"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9" v-if="orderType === '售后工单'">
            <el-form-item label="联系人/电话:" prop="customerPhone">
              <el-input
                v-model="detailForm.customerPhone"
                placeholder="请输入联系人/电话"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :offset="3" :span="9" v-if="orderType === '售后工单'">
            <el-form-item label="关联订单:" prop="order">
              <el-input
                v-model="detailForm.linkOrderCn"
                placeholder="请选择订单"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9" v-if="orderType === '售后工单'">
            <el-form-item label="客户地址:" prop="customerAddress">
              <el-input
                v-model="detailForm.customerAddress"
                placeholder="请输入地址"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :offset="3" :span="9" v-if="orderType === '售后工单'">
            <el-form-item label="关联项目:" prop="project">
              <el-input
                v-model="detailForm.linkProjectCn"
                disabled
                placeholder="请选择项目"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="9" v-if="orderType === '售后工单'">
            <el-form-item label="关联产品:" prop="product">
              <el-select
                v-model="detailForm.linkProduct"
                disabled
                placeholder="请选择产品"
              >
                <el-option
                  v-for="(item, index) in related_products"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 研发工单 -->
          <el-col :offset="3" :span="9" v-if="orderType === '研发工单'">
            <el-form-item label="系统/项目名称:" prop="projectName">
              <el-select v-model="detailForm.projectName" disabled>
                <el-option
                  v-for="item in system_or_project_name"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="9" v-if="orderType === '研发工单'">
            <el-form-item label="期望完成时间:" prop="expectedEndTime">
              <el-date-picker
                v-model="detailForm.expectedEndTime"
                type="date"
                placeholder="选择时间"
                value-format="YYYY-MM-DD"
                disabled
              />
            </el-form-item>
          </el-col>
          <!--  -->
          <el-col :offset="3" :span="15">
            <el-form-item label="工单描述:" prop="details">
              <el-input
                type="textarea"
                placeholder="输入内容"
                :rows="7"
                maxlength="300"
                show-word-limit
                v-model="detailForm.details"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :offset="3" :span="15">
            <el-form-item label="附件:" prop="附件">
              <div class="text-14px" style="width: 100%">
                <div v-for="item in fileList" :key="item.fileId">
                  <a style="color: #409eff" :href="item.url">{{
                    item.origFileName
                  }}</a>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="part" v-if="resultForm.length">
        <title-name
          :title="`工单完成情况`"
          icon="i-carbon-bookmark-filled"
        ></title-name>
      </div>
      <div v-if="resultForm.length">
        <template v-for="(item, i) in resultForm" :key="i">
          <el-col :offset="3" :span="15" class="resultCard">
            <el-form label-width="120px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="完成情况说明:">
                    <div>{{ item.scheduleRemark }}</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="完成率:">
                    <span>{{ item.schedule }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="附件:">
                <div class="text-14px" style="width: 100%">
                  <div v-for="v in item.files" :key="v.fileId">
                    <a style="color: #409eff" :href="v.url">{{
                      v.origFileName
                    }}</a>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </el-col>
        </template>
      </div>
      <div class="part" v-if="FeedbackResult.length">
        <title-name
          :title="`结果反馈`"
          icon="i-carbon-bookmark-filled"
        ></title-name>
      </div>
      <div v-if="FeedbackResult.length">
        <Feedback :FeedbackResult="FeedbackResult"></Feedback>
      </div>
    </div>
  </div>
</template>

<script setup>
import Feedback from './feedback.vue'
import useUserStore from '@/store/modules/user'
import {
  work_order_type,
  work_order_level,
  system_or_project_name,
  related_products
} from '@/hooks/dict/business'
import { workOrderDetails, detailByWorkId } from '@/api/rsgl/order'
import { treeselectNoPriv } from '@/api/rsgl/zzjg'

const route = useRoute()
const router = useRouter()
const baseForm = ref({
  level: 3,
  sponsorName: '',
  companyName: '',
  deptName: '',
  sponsorPhone: ''
})
const resultForm = ref({})
const detailForm = ref({})
const FeedbackResult = ref([])
const processOver = ref(false)
watch(
  () => route.query.id,
  val => {
    if (val) {
      workOrderDetails(val).then(res => {
        console.log(res)
        const resp = res.data
        if (resp.processState === '审批通过') {
          processOver.value = true
        }
        // 基本信息
        baseForm.value.theme = resp.theme
        baseForm.value.num = resp.num
        baseForm.value.level = resp.level
        baseForm.value.type = resp.type
        baseForm.value.fileNames = (resp.sysAttachFiles || []).map(
          v => v.fileName
        )
        baseForm.value.sponsorName = resp.sponsorName
        baseForm.value.companyName = resp.companyName
        baseForm.value.deptName = resp.deptName
        baseForm.value.sponsorPhone = resp.sponsorPhone
        fileList.value = resp.sysAttachFiles
        // 详细信息
        changeType(baseForm.value.type)
        detailForm.value.customerAddress = resp.workOrderExtVo.customerAddress
        detailForm.value.customerPhone = resp.workOrderExtVo.customerPhone
        detailForm.value.details = resp.workOrderExtVo.details
        detailForm.value.customerId = resp.workOrderExtVo.customerId
        detailForm.value.customerIdCn = resp.workOrderExtVo.customerIdCn
        detailForm.value.linkOrder = resp.workOrderExtVo.linkOrder
        detailForm.value.linkOrderCn = resp.workOrderExtVo.linkOrderCn
        detailForm.value.linkProduct = resp.workOrderExtVo.linkProduct
        detailForm.value.linkProject = resp.workOrderExtVo.linkProject
        detailForm.value.linkProjectCn = resp.workOrderExtVo.linkProjectCn
        detailForm.value.projectName = resp.workOrderExtVo.projectName
        detailForm.value.expectedEndTime = resp.workOrderExtVo.expectedEndTime
      })
      detailByWorkId({ workId: val }).then(res => {
        // 工单完成情况
        resultForm.value = res.data.taskScheduleDetailVo || []
        // 设置files
        resultForm.value.forEach(val => {
          const origFileName = val.scheduleFileName.split(',')
          const url = val.scheduleFilePath.split(',')
          val.files = origFileName.map((v, i) => {
            const obj = {
              origFileName: v,
              url: url[i],
              fileId: v + url[i]
            }
            return obj
          })
        })

        // 结果反馈
        FeedbackResult.value = res.data.operateFkList || []
      })
    }
  },
  { deep: true, immediate: true }
)

const ToProcess = ref(false)
watch(
  () => route.query.procInsId,
  val => {
    if (val) {
      ToProcess.value = false
    } else {
      ToProcess.value = true
    }
  },
  { deep: true, immediate: true }
)

// 跳转流程详情
function toProcessDetail() {
  router.push({
    path: '/process/workDetail',
    query: {
      procInsId: route.query.procInsId,
      //   taskId: row.taskId,
      processed: false
    }
  })
}
const workOrderType = computed(() => arrayToTree(ref(work_order_type).value)) // 工单类型树结构
const org = ref('')
const dept = ref('')
// 获取登录者公司部门
async function initData() {
  const list = await treeselectNoPriv()
  const orgObj = list.data[0].children.find(
    v => v.id === userStore.userInfo.orgId
  )
  org.value = orgObj?.label
  dept.value = orgObj.children.find(
    v => v.id === userStore.userInfo.deptId
  )?.label
}
initData()
const userStore = useUserStore()
const fileList = ref([])

const orderType = ref('普通工单')
function changeType(val) {
  const findVal = ref(work_order_type).value.find(v => v.value === val)
  orderType.value = findVal.label
  if (findVal.parentId) {
    orderType.value = ref(work_order_type).value.find(
      v => v.value === findVal.parentId
    ).label
  }
}
// 转任务
function transFormTask() {
  sessionStorage.setItem(
    'workOrderForm',
    JSON.stringify({
      level: baseForm.value.level, // 级别
      theme: baseForm.value.theme, //主图
      details: detailForm.value.details, //描述
      workOrderId: route.query.id, //工单id
      customerId: detailForm.value.customerId, // 客户id
      linkOrder: detailForm.value.linkOrder, // 订单id
      linkProduct: detailForm.value.linkProduct, // 产品id
      linkProject: detailForm.value.linkProject, // 项目id
      linkOrderCn: detailForm.value.linkOrderCn, // 订单名称
      customerIdCn: detailForm.value.customerIdCn, // 客户名称
      linkProductCn: detailForm.value.linkProductCn, // 产品名称
      linkProjectCn: detailForm.value.linkProjectCn, // 项目名称
      projectName: detailForm.value.projectName, //系统/项目名称
      customerPhone: detailForm.value.customerPhone, // 联系人电话
      customerAddress: detailForm.value.customerAddress, // 客户地址
      fileList: fileList.value // 附件
    })
  )
  router.push({
    path: 'addTasking',
    query: {
      workOrderTransform: true,
      flag: 'add'
    }
  })
}

// 数组转换树
/**
 * @params arr 输入数组
 * @params nodeKey 树唯一标识
 * @params parentId 父id
 *
 */
function arrayToTree(arr, nodeKey = 'value', parentId = 'parentId') {
  const mapObj = new Map()
  const result = []
  arr.forEach(v => {
    mapObj.set(v.value, v)
  })
  for (const [key, val] of mapObj) {
    if (val.parentId && mapObj.has(val.parentId)) {
      if (!mapObj.get(val.parentId).children) {
        mapObj.get(val.parentId).children = []
      }
      const some = mapObj.get(val.parentId).children.some(v => {
        return v.value === val.value
      })
      if (!some) {
        mapObj.get(val.parentId).children.push(val)
      }
    } else {
      result.push(mapObj.get(key))
    }
  }
  return result
}
</script>

<style scoped lang="scss">
.workOrderDetail {
  .part {
    @apply my-20px;
  }
  :deep(.el-select) {
    width: 100%;
  }
  .resultCard {
    @apply relative  p-20px text-14px mb-20px;
    border: 1px solid rgb(230, 223, 223);
    border-radius: 8px;
    box-shadow: 0px 0px 5px #ccc;
  }
}
</style>
